//
//  UserInfo.m
//  KidReading
//
//  Created by telen on 16/3/23.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "UserInfo.h"
#import "ConstDefine.h"

#pragma mark- UserInfo

@implementation UserInfo
{
    NSArray* tempBougthBookIdsArr;
}

#pragma mark- 一账通映射

-(NSString *)userName{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.nickname;
//    }
    return @"";
}

- (NSInteger)uid
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return (NSInteger)wyUser.uid;
//    }
    return 0;
}

- (NSString *)uCode
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.qrcode;
//    }
    return @"";
}

- (NSString*)catoken
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.token;
//    }
    return nil;
}

- (NSString*)country_code
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.area;
//    }
    return nil;
}

- (NSInteger)role
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.role;
//    }
    return 0;
}

- (BOOL)isGuest
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return wyUser.isTouristAcount;
//    }
    return YES;
}

- (NSInteger)gender {
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if (wyUser) {
//        return [wyUser.gender integerValue];
//    }
    return 0;
}

#pragma mark-
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:[self token] forKey:NSStringFromSelector(@selector(token))];
    [aCoder encodeObject:[self selfVip] forKey:NSStringFromSelector(@selector(selfVip))];
    [aCoder encodeObject:[self schoolVip] forKey:NSStringFromSelector(@selector(schoolVip))];
    [aCoder encodeObject:[self familyVip] forKey:NSStringFromSelector(@selector(familyVip))];
    [aCoder encodeObject:[self titleBar] forKey:NSStringFromSelector(@selector(titleBar))];
    [aCoder encodeObject:[self show] forKey:NSStringFromSelector(@selector(show))];
    [aCoder encodeObject:[self boughtBookIds] forKey:NSStringFromSelector(@selector(boughtBookIds))];
    //
    [aCoder encodeInteger:[self s_flag] forKey:NSStringFromSelector(@selector(s_flag))];
    [aCoder encodeObject:[self totalSub] forKey:NSStringFromSelector(@selector(totalSub))];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self != nil) {
        self.token = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(token))];
        self.selfVip = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(selfVip))];
        self.schoolVip = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(schoolVip))];
        self.familyVip = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(familyVip))];
        self.titleBar = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(titleBar))];
        self.show = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(show))];
        self.boughtBookIds = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(boughtBookIds))];
        //
        self.s_flag = [aDecoder decodeIntegerForKey:NSStringFromSelector(@selector(s_flag))];
        self.totalSub = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(totalSub))];
    }
    
    return self;
}

- (BOOL)isGuest_exp_device
{
    BOOL guest = self.isGuest;
    if (guest) {
         guest = ![[CacheData shareSingle] isLockedDeviceLogin];
    }
    return guest;
}

- (BOOL)isAnySelfVipEnable
{
    NSArray* keys = _selfVip.allKeys;
    for (NSString* key in keys) {
        if ([self isVipEnable:key]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)isAnyKindsVipEnable {
    NSArray* selfkeys = _selfVip.allKeys;
    for (NSString* key in selfkeys) {
        if ([self isVipEnable:key]) {
            return YES;
        }
    }
    NSArray* schoolkeys = _schoolVip.allKeys;
    for (NSString* key in schoolkeys) {
        if ([self isVipEnable:key]) {
            return YES;
        }
    }
    NSArray* famliykeys = _familyVip.allKeys;
    for (NSString* key in famliykeys) {
        if ([self isVipEnable:key]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)isVipEnable:(NSString*)viptype;
{
    if (_selfVip && [_selfVip isKindOfClass:[NSDictionary class]] && [self isVIPOK:_selfVip vipType:viptype]) {
        return YES;
    }
    if (_schoolVip && [_schoolVip isKindOfClass:[NSDictionary class]] && [self isVIPOK:_schoolVip vipType:viptype]) {
        return YES;
    }
    if (_familyVip && [_familyVip isKindOfClass:[NSDictionary class]] && [self isVIPOK:_familyVip vipType:viptype]) {
        return YES;
    }
//    if (_schoolVip && [_schoolVip isKindOfClass:[NSDictionary class]]) {
//        for (NSDictionary* dict in _schoolVip) {
//            if (dict && [dict isKindOfClass:[NSDictionary class]] && isVIPOK(dict)) {
//                return YES;
//            }
//        }
//    }
//    if (_familyVip && [_familyVip isKindOfClass:[NSDictionary class]]) {
//        for (NSDictionary* dict in _familyVip) {
//            if (dict && [dict isKindOfClass:[NSDictionary class]] && isVIPOK(dict)) {
//                return YES;
//            }
//        }
//    }
    return NO;
}

- (BOOL)isVIPOK:(NSDictionary*)dic vipType:(NSString *)viptype{
    LongLong now = [DataProcessing timestampFromNSDate:[NSDate date]];
    nullToNil(dic);
    NSDictionary* dict = dic[viptype];
    nullToNil(dict);
    if(dict){
        NSNumber* bg = dict[@"limitStart"];
        NSNumber* ed = dict[@"limitEnd"];
        nullToNil(bg);
        nullToNil(ed);
        LongLong begin = [bg longLongValue];
        LongLong end = [DataProcessing timestampFromtimestamp_tilDayEnd:[ed longLongValue]];
        if (now >= begin && now < end) {
            return YES;
        }
    }
    return NO;
}


- (BOOL)isInfo_OK
{
//    WYUser* wyUser = [WY3SDKLogin currentUser];
//    if(wyUser && [wyUser exist]){
//        if (self.token.length > 0 && self.country_code.length > 0 && self.uid > 0) {
//            return YES;
//        }
//    }
    return NO;
}

- (NSString *)vipPayInfoShow:(NSArray *)vipCodeArr
{
    NSDictionary* dic = self.show[@"payShow"];
    nullToNil(dic);
    if (dic){
        //
        if (vipCodeArr.count > 1) {
            NSString* zh = dic[@"titleZh"];
            NSString* en = dic[@"titleEn"];
            return [DataProcessing chooseLanguageFromCN:zh andEN:en];
        }else if (vipCodeArr.count == 1){
            NSString* vipCode = vipCodeArr.firstObject;
            NSDictionary* dict = dic[vipCode];
            NSString* zh = dict[@"titleZh"];
            NSString* en = dict[@"titleEn"];
            return [DataProcessing chooseLanguageFromCN:zh andEN:en];
        }
    }
    return nil;
}

- (NSString *)vipPayItemShow:(NSString *)vipCode
{
    NSDictionary* dic = self.show[@"payShow"];
    nullToNil(dic);
    if (!dic)return vipCode;
    //
    NSDictionary* dict = dic[vipCode];
    NSString* zh = dict[@"itemZh"];
    NSString* en = dict[@"itemEn"];
    if ((!zh && [DataProcessing shareSingle].isChineseForLocalSystem)
        || (!en && ![DataProcessing shareSingle].isChineseForLocalSystem)) {
        return vipCode;
    }
    return [DataProcessing chooseLanguageFromCN:zh andEN:en];
}

- (NSArray*)vipSetInfoShow
{
    NSMutableArray* marr = [NSMutableArray new];
    LongLong now = [DataProcessing timestampFromNSDate:[NSDate date]];
    
    //副本标题
    NSString*(^getVIPOK_subTitle)(NSDictionary*) = ^(NSDictionary* dict){
        nullToNil(dict);
        if(dict){
            NSNumber* bg = dict[@"limitStart"];
            NSNumber* ed = dict[@"limitEnd"];
            nullToNil(bg);
            nullToNil(ed);
            LongLong begin = [bg longLongValue];
            LongLong end = [DataProcessing timestampFromtimestamp_tilDayEnd:[ed longLongValue]];
            if (now >= begin && now < end) {
                NSString* bgStr = [[DataProcessing dateFromtimestamp:begin] stringWithFormat:@"yyyy.MM.dd"];
                NSString* edStr = [[DataProcessing dateFromtimestamp:end] stringWithFormat:@"yyyy.MM.dd"];
                return [NSString stringWithFormat:@"%@-%@",bgStr,edStr];
            }
        }
        return @"";
    };
    
    //标题
    NSString*(^getVIP_Title)(NSDictionary*, int*) = ^(NSDictionary* dict, int* ableExtend){
        nullToNil(dict);
        if(dict){
            NSString* zh = dict[@"titleZh"];
            NSString* en = dict[@"titleEn"];
            NSNumber* ab = dict[@"ableExtend"];
            nullToNil(zh);
            nullToNil(en);
            nullToNil(ab);
            *ableExtend = [ab intValue];
            return [DataProcessing chooseLanguageFromCN:zh andEN:en];
        }
        return @"";
    };
    
    //unvip info
    void(^getUnVip_Info)(NSDictionary*, int*, NSString**, NSString**) = ^(NSDictionary* dict, int* ableExtend,NSString** title,NSString** subtitle){
        nullToNil(dict);
        if(dict){
            NSString* zh = dict[@"titleZh"];
            NSString* en = dict[@"titleEn"];
            NSNumber* ab = dict[@"ableExtend"];
            nullToNil(zh);
            nullToNil(en);
            nullToNil(ab);
            *ableExtend = [ab intValue];
            *title = [DataProcessing chooseLanguageFromCN:zh andEN:en];
            zh = dict[@"subtitleZh"];
            en = dict[@"subtitleEn"];
            nullToNil(zh);
            nullToNil(en);
            *subtitle = [DataProcessing chooseLanguageFromCN:zh andEN:en];
        }
    };
    
    //添加项
    NSArray* (^addItems)(NSDictionary*, int) = ^(NSDictionary* dic, int btnAble){ //btnAble  1,扩展   2,开通
        nullToNil(dic);
        NSMutableArray* addmarr = [NSMutableArray new];
        [dic enumerateKeysAndObjectsUsingBlock:^(NSString*  _Nonnull vipCode, NSDictionary*  _Nonnull dict, BOOL * _Nonnull stop) {
            if(btnAble == 1){
                NSString* subTitle = getVIPOK_subTitle(dict);
                if (subTitle.length > 1) {
                    int ableExtend = 0;
                    NSString* title = getVIP_Title(dict,&ableExtend);
                    if (ableExtend > 0) ableExtend = 1;
                    if(title && subTitle)[addmarr addObject:@{@"title":title,@"subTitle":subTitle,@"btnAble":@(ableExtend),@"vipCode":vipCode}];
                }
            }
            if(btnAble == 2){
                NSString* title = nil;
                NSString* subTitle = nil;
                int ableExtend = 0;
                getUnVip_Info(dict,&ableExtend,&title,&subTitle);
                if (ableExtend > 0) ableExtend = 2;
                if(title && subTitle)[addmarr addObject:@{@"title":title,@"subTitle":subTitle,@"btnAble":@(ableExtend),@"vipCode":vipCode}];
            }
        }];
        return addmarr;
    };
    
    NSArray* myArr = addItems(self.selfVip,1);
    NSArray* faArr = addItems(self.familyVip,1);
    NSArray* shArr = addItems(self.schoolVip,1);
    NSArray* unArr = @[];
    if (self.s_flag != 1) {
        unArr = addItems(self.show[@"unvipShow"],2);
    }
    [marr addObjectsFromArray:myArr];
    [marr addObjectsFromArray:faArr];
    [marr addObjectsFromArray:shArr];
    [unArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString* unvipCode = obj[@"vipCode"];
        BOOL havaTheCode = NO;
        for (NSDictionary* dc in myArr) {
            NSString* vipCode = dc[@"vipCode"];
            if ([vipCode isEqualToString:unvipCode]) {
                havaTheCode = YES;
                break;
            }
        }
        if (!havaTheCode) {
            [marr addObject:obj];
        }
    }];
    return marr;
}

- (NSString *)vipGridInfoShow:(NSString *)vipCode
{
    //副本标题
    NSString*(^getVIPOK_subTitle)(NSDictionary*) = ^(NSDictionary* dict){
        nullToNil(dict);
        if(dict){
            NSNumber* bg = dict[@"limitStart"];
            NSNumber* ed = dict[@"limitEnd"];
            nullToNil(bg);
            nullToNil(ed);
            LongLong begin = [bg longLongValue];
            LongLong end = [DataProcessing timestampFromtimestamp_tilDayEnd:[ed longLongValue]];
            LongLong now = [DataProcessing timestampFromNSDate:[NSDate date]];
            if (now >= begin && now < end) {
                NSString* bgStr = [[DataProcessing dateFromtimestamp:begin] stringWithFormat:@"yyyy.MM.dd"];
                NSString* edStr = [[DataProcessing dateFromtimestamp:end] stringWithFormat:@"yyyy.MM.dd"];
                return [NSString stringWithFormat:@"(%@-%@)",bgStr,edStr];
            }
        }
        return @"";
    };
    
    if (vipCode && vipCode.length > 0) {
        return getVIPOK_subTitle(self.selfVip[vipCode]);
    }
    return @"";
}

- (void)setBoughtBookIds:(NSString *)boughtBookIds
{
    _boughtBookIds = boughtBookIds;
    tempBougthBookIdsArr = [_boughtBookIds componentsSeparatedByString:@","];
}
- (BOOL)isBoughtBookId:(NSInteger)bookid
{
    if (_boughtBookIds) {
        if(tempBougthBookIdsArr==nil)tempBougthBookIdsArr = [_boughtBookIds componentsSeparatedByString:@","];
        for (NSString* value in tempBougthBookIdsArr) {
            NSInteger bkid = value.integerValue;
            if (bkid == bookid) {
                return YES;
            }
        }
    }
    return NO;
}

- (void)savePush_deviceToken:(NSString*)deviceToken
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:deviceToken forKey:@"push-deviceToken"];
    [userDefaults synchronize];
}

- (NSString*) loadPush_deviceToken
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    return [userDefaultes stringForKey:@"push-deviceToken"];
}

- (void)logout
{
//    [[RootViewController shareLastInstance] stopAudioPlay:YES];
//    [WY3SDKLogin logOut];
    [[CacheData shareSingle] saveUserLoginInfo:nil];
}

- (BOOL)authorityForbook:(TABLE_BOOKS *)tb_book currentVC:(BaseViewController*)currentVC{
    //时间限制
    if (![[DBHelper shareInstance] isUserTimeOK]) {
        //[[RootViewController shareLastInstance] load_UserInfo_Server_Login:nil];
        return YES;
    }
    //免费判断
    BOOL isfree = NO;
    if (tb_book.freeflag ==  bookshelf_saleFlag_type_free || tb_book.freeflag == bookshelf_saleFlag_type_LimitTime || tb_book.freeflag == bookshelf_saleFlag_type_opus) {
        isfree = YES;
        return NO;
    }
//    //权限判断
//    NSDictionary *currentPaystyle = tb_book.payStyle;
//    if (currentPaystyle && !isfree) {
//        // vip
//        NSArray *saleStyle = [currentPaystyle valueForKey:@"saleStyle"];
//        NSArray *ownStyle = [currentPaystyle valueForKey:@"ownStyle"];
//        //
//        NSString *single = [currentPaystyle valueForKey:@"singleStyle"];
//        
//        // 单本购买过
//        __block BOOL isBuyed = NO;
//        if (single && [single isEqualToString:@"single"]) {
//            if ([self isBoughtBookId:tb_book.bookId]) {
//                isBuyed = YES;
//            }
//        }
//        // vip有权限
//        if(!isBuyed) {
//            [ownStyle enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                if ([self isVipEnable:obj]) {
//                    isBuyed = YES;
//                }
//            }];
//        }else {
//            return NO;
//        }
//        // 需要产生购买行为
//        if (!isBuyed) {
//            // retail
//
//            NSString *bookTitle = [DataProcessing chooseLanguageFromCN:tb_book.name_zh andEN:tb_book.name_en];
//            if (single && [single isEqualToString:@"single"]) {
//                NSDictionary *singleData = [currentPaystyle valueForKey:@"singleData"];
//                if (singleData) {
//                    [currentVC saveSingleProductWithSinleDic:singleData];
//                    //retail only
//                    if ([DataProcessing isProductExist] && !saleStyle.count) {
//                        if (currentVC) {
//                           [currentVC showAlertMsgBuyWithBuyType:SingleBuyType_SinglePurchase vipTypes:nil BookTitle:bookTitle tbBook:tb_book];
//                        }
//                        
//                        return YES;
//                    }
//                    // retail&&Vip Mix
//                    if ([DataProcessing isProductExist] && saleStyle.count) {
//                        if (currentVC) {
//                           [currentVC showAlertMsgBuyWithBuyType:SingleBuyType_MixedPurchase vipTypes:saleStyle BookTitle:bookTitle tbBook:tb_book];
//                        }
//                        
//                        return YES;
//                    }
//                }
//            }
//            // vip only
//            else if (saleStyle.count) {
//                if (!self.isInfo_OK) {
//                    if (currentVC) {
//                      [currentVC showAlertMsgMustLogin];
//                    }
//                    return YES;
//                }else {
//                    if (currentVC) {
//                       [currentVC showAlertMsgBuyWithBuyType:BuyVIP_Login_Purchase vipTypes:saleStyle BookTitle:bookTitle tbBook:tb_book];
//                    }
//                    return YES;
//                }
//            }
//            else {
//                if (currentVC) {
//                    [[WaitingShow shareSingleShow] showString:NSLocalizedString(@"needupdateapp", nil) andAutoHide:YES];
//                    [[RootViewController shareLastInstance] checkUpate_App];
//                }
//                return YES;
//            }
//        }
//    }
    return NO;
}

@end


